﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;

namespace Framework.WebmasterTool.Contacts
{
    public partial class ContactDetails : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                CallCkeditors();
                LoadContactDetails();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Contact.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void CallCkeditors()
        {
            Globals.CallCKFinder(txtBody);
        }

        public void LoadContactDetails()
        {
            if (Request.QueryString["ContactID"] != null)
            {
                int contactID;
                int.TryParse(Request.QueryString["ContactID"], out contactID);
                udv_Contact contactDetails = entity.udv_Contact.Where(ct => ct.ContactID == contactID).FirstOrDefault();
                if (contactDetails != null)
                {
                    var contactAnswers = entity.udv_ContactAnswer.Where(cs => cs.udv_Contact.ContactID == contactID).ToList();
                    contactDetails.ViewStatus = true;
                    lblFullname.Text = contactDetails.FullName.Trim();
                    lblAddress.Text = contactDetails.Address.Trim();
                    lblPhone.Text = contactDetails.Tel.Trim();
                    lblEmail.Text = contactDetails.Email.Trim();
                    lblTitle.Text = contactDetails.Title.Trim();
                    lblContent.Text = contactDetails.Content;
                    lblAddedDate.Text = String.Format("{0:dd/MM/yyyy HH:mm:ss tt}", contactDetails.AddedDate);
                    entity.SaveChanges();
                    lblCountContactAnswer.Text = contactAnswers.Count.ToString();
                    aContactAnswers.HRef = "ContactAnswer.aspx?ContactID=" + contactID;
                    lblContactUpdatedDate.Text = String.Format("{0:dd/MM/yyyy HH:mm:ss tt}", contactDetails.UpdatedDate);
                    lblContactUpdatedBy.Text = contactDetails.UpdatedBy;
                    if (contactAnswers.Count == 0)
                    {
                        aContactAnswers.Visible = false;
                    }
                }
                else
                {
                    Response.Redirect("Default.aspx");
                }
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
        }

        private bool SendEmail(string Subject, string Content, string email)
        {
            udv_EmailHostSetting emailHostSetting = entity.udv_EmailHostSetting.OrderByDescending(es => es.EmailHostSettingID).FirstOrDefault();
            string serverMail = emailHostSetting.ServerMailSMTP.Trim();
            string port = emailHostSetting.PortMailSMTP.ToString();
            string yourMailAccount = emailHostSetting.MailAccount.Trim();
            string yourMailPassword = Globals.Base64Decode(emailHostSetting.Password.Trim());

            SendMail sm = new SendMail();
            sm.ServerMail = serverMail;
            sm.ServerPort = port;
            sm.SSL = emailHostSetting.SSL.Value;
            sm.YourMailAccount = yourMailAccount;
            sm.YourMailPassword = yourMailPassword;
            sm.SetUpYourServerMail();

            string receive = email.Trim();
            string title = Subject;

            string body = Content;

            sm.CreateMailObject(receive, body, title, emailHostSetting.MailReceive);
            if (sm.MailSending())
            {
                lblMsg.Text = "Gửi mail thành công";
                return true;
            }
            else
            {
                lblMsg.Text = "Lỗi cấu hình mail server. Vui lòng cấu hình lại mail server và thử lại sau";
                return false;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["ContactID"] != null)
            {
                int contactID;
                int.TryParse(Request.QueryString["ContactID"], out contactID);
                udv_Contact contactDetails = entity.udv_Contact.Where(ct => ct.ContactID == contactID).FirstOrDefault();
                if (contactDetails != null)
                {
                    contactDetails.ReplyStatus = true;
                    entity.SaveChanges();
                    udv_ContactAnswer contactAnswers = new udv_ContactAnswer();

                    contactDetails.UpdatedDate = DateTime.Now;
                    contactDetails.UpdatedBy = Membership.GetUser().UserName;

                    contactAnswers.udv_Contact = contactDetails;
                    contactAnswers.AnswerTitle = txtAnswerTitle.Text.Trim();
                    contactAnswers.AnswerContent = txtBody.Text;
                    contactAnswers.AddedDate = DateTime.Now;
                    contactAnswers.AddedBy = Membership.GetUser().UserName;

                    if (SendEmail(txtAnswerTitle.Text.Trim(), txtBody.Text, lblEmail.Text.Trim()))
                    {
                        entity.AddToudv_ContactAnswer(contactAnswers);
                        entity.SaveChanges();
                        //create db log
                        contactAnswers.udv_ContactReference.Load();
                        CreateDBLog(null, null, TypeAction.None, "Gửi mail liên hệ: " + contactAnswers.udv_Contact.Title + " - " + string.Format("{0:dd/MM/yyyy HH:mm:ss}", contactAnswers.AddedDate), contactAnswers.AnswerTitle, contactAnswers.AnswerContent, "", "",
                                "", "", "", "");
                        Response.Redirect("Default.aspx");
                    }
                }
                else
                {
                    lblMsg.Text = "Liên hệ không tồn tại";
                }
            }
            else
            {
                lblMsg.Text = "Liên hệ không tồn tại";
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("Default.aspx");
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}